package com.wmh.baseservice.common.wechat.ma.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.BaseWxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.common.utils.encrypt.RSAUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Api(tags = "微信小程序 - 用户接口")
@RestController
@RequestMapping("/wx/ma/user")
public class WxMaUserController {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private WxMpService wxMpService;

    @ApiOperation("授权登录")
    @GetMapping("public/login")
    public String login(String code, Long parentId) {
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            LogUtil.info(session.getSessionKey());
            LogUtil.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            JSONObject objects = usInfoService.login(session.getOpenid(), parentId);
            objects.put("sessionKey", session.getSessionKey());
            return objects.toJSONString();
        } catch (WxErrorException e) {
            LogUtil.error(e.getMessage(), e);
            return e.toString();
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    @RequiresRoles("user")
    public String info(String sessionKey, String signature, String rawData, String encryptedData, String iv) throws Exception {
        sessionKey = RSAUtil.decryptByPrivateKey(sessionKey);
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
//        WxMpUser user = wxMpService.getUserService().userInfo("o0g7e6ubn7WGOuos9V4s1dFFRHTU");
//        LogUtil.info("获取到的用户名称:{}",CommUtil.checkNull(user)?user.getNickname():"空");
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (CommUtil.checkNull(usInfo)) {
            usInfo.setOpenId(userInfo.getOpenId()).setAvatar(userInfo.getAvatarUrl()).setNick(userInfo.getNickName());
            if (!usInfoService.updateById(usInfo)) {
                return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
            }
        }
        return ReturnBody.success(usInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    @RequiresRoles("user")
    public String phone(String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        return JSONObject.toJSONString(phoneNoInfo);
    }

    @ApiOperation("")
    @GetMapping("public/test")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String asd() {
        WxMaConfig wxMaConfig = wxMaService.getWxMaConfig();
        System.out.println(wxMaConfig.getAppid());
        Map<String, WxMaConfig> map = new HashMap<>();
        wxMaService.setMultiConfigs(map);
        return ReturnBody.success();
    }

}
